/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lab2sum;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Daryna_Ragimova
 */
public class Calculation {

    private final int threadsNumber;
    private final int N;
    private List<OneThread> threads = new ArrayList<OneThread>();
    private double sum = 0.0;

    public Calculation(int n, int threadsNumber) {
        this.N = n;
        this.threadsNumber = threadsNumber;
    }

    public double process() {

        int forProcess = (2 * N + 1) / threadsNumber;
        if ((2 * N + 1) % threadsNumber > forProcess / 2) {
            forProcess++;
        }
        for (int i = 0; i < threadsNumber; i++) {
            int first = -N + forProcess * i;
            int last = -N + forProcess * (i + 1);
            if (last >= N) {
                last = N + 1;
            }
            OneThread currentThread = new OneThread(first, last);
            threads.add(currentThread);
            currentThread.start();
        }
        for (OneThread t : threads) {
            try {
                t.join();
                sum += t.getSum();
            } catch (InterruptedException ex) {
                Logger.getLogger(Calculation.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return sum;
    }
}
    



